package cloudLibrary;

import java.io.IOException;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;



/*
 * this class registers a user in the Users table of the database. 
 */

@SuppressWarnings("serial")
public class BorrowItemServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null)
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI())); // demand
																				// user
																				// to
																				// be
																				// logged
																				// in.
		String itemID = "";
		Item item = null;

		try {
			itemID = req.getParameter("itemID");

		} catch (Exception e) {
			// ??
		}
		if (itemID == null) {
		} else {
			PersistenceManager pm = PMF.get().getPersistenceManager();

			try {
				String query = "select from " + Item.class.getName();
				List<Item> items = (List<Item>) pm.newQuery(query).execute();
				
				long id = Long.parseLong(itemID.trim());
				for (Item i : items) {
					if (i.getItemID().getId() == id) {
							item = i;
						}
					}
		        Properties props = new Properties();
		        Session session = Session.getDefaultInstance(props, null);

		        String msgBody = "Hi,\n" +
		        		"This is a request from " + user.getEmail() + ". This user of Cloud Computing Library would like to borrow you the " +
		        				item.getType() + " " + item.getTitle() + " from your own library. If you agree, contact him to set the exchange.";

		        try {
		            Message msg = new MimeMessage(session);
		            msg.setFrom(new InternetAddress(user.getEmail(), user.getNickname()));
		            msg.addRecipient(Message.RecipientType.TO,
		                             new InternetAddress(item.getOwner(), "Owner"));
		            msg.setSubject("Library request");
		            msg.setText(msgBody);
		            Transport.send(msg);
		            resp.sendRedirect("/index.jsp?msg=requestsent");

		        } catch (AddressException e) {
		            resp.getWriter().println("AddressException");
		        } catch (MessagingException e) {
		        	resp.getWriter().println("MessagingException");
		        }
		        
		        
		        
		        
		        

				

			 finally {
				pm.close();
			}
			}
			catch (Exception e) {
			}
			}
	}
}
